package com.fw.kafka.product;

import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * @Author:yanwei
 * @Date: 2020/9/19 - 22:19
 */
@CrossOrigin
@RestController
public class ProductController {
    @Resource
    private KafkaTemplate template;

    private static final String topic = "fw_boot";

    /**
     * 发送普通消息
     * @param mes
     * @return
     */
    @GetMapping("/put/{mes}")
    public String put(@PathVariable String mes){
        template.send(topic,mes);
        if ("error".equals(mes)) throw  new RuntimeException("自定义异常");
        template.send(topic,mes.concat("\r++"));
        return mes;
    }

    /**
     * 事务驱动消息 1
     */
    @GetMapping("/put1/{mes}")
    public String put1(@PathVariable String mes){
        template.executeInTransaction(item ->{
            item.send(topic,mes);
            if ("error".equals(mes)) throw  new RuntimeException("自定义异常");
            template.send(topic,mes.concat("\r++"));
            return Boolean.TRUE;
        });
        return mes;
    }

    /**
     * 事务驱动消息 2
     */

    @GetMapping("/put2/{mes}")
    @Transactional(rollbackFor = Exception.class)
    public String put2(@PathVariable String mes){
        template.send(topic,mes);
        if ("error".equals(mes)) throw  new RuntimeException("自定义异常");
        template.send(topic,mes.concat("\r++"));


        return mes;
    }
}
